package com.sdata.service;


import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sdata.meta.commons.info.Context;
import com.sdata.meta.commons.info.SmsContext;
import com.sdata.meta.commons.sys.UserItem;
import com.sdata.sdk.meta.foundation.pojo.SDExceptionEntity;
import com.sdata.sdk.service.system.system.service.SDSysConfigService;
import com.sdata.system.service.info.MsgCenterService;
import com.sdata.system.service.info.SmsMsgObserver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

/**
 * 二开验证码短信平台
 */
@Slf4j
@Service
public class CustomizeSmsService implements SmsMsgObserver {

    @Resource(name = "SDSysConfigServiceImpl")
    private SDSysConfigService sdSysConfigService;

    /**
     * 注册短信平台观察者
     */
    @PostConstruct
    public void signSMSCustomizeMsg() {
        MsgCenterService msgCenterService = new MsgCenterService();
        // key 是和前端约定好的值,不能和其他的重复
        boolean signResult = msgCenterService.registerSMSObserver("xxxxx", this);
        if (signResult) {
            log.info("xxxxx SMS platform successfully registered");
        } else {
            log.info("xxxxx cloud SMS platform observer object already exists");
        }
    }

    /**
     * 发送短信验证码
     */
    @Override
    public boolean sendSmsMsg(String title, List<String> user_id, Context context, List<UserItem> userItems, String contact) {
        log.info("title: {}, user_id:{}, context: {}, userItems:{}, contact:{}", title, user_id, context, userItems, contact);
        // context包含短信验证码，contact是手机号
        SmsContext smsContext = (SmsContext) context;
        return send(smsContext.getCode(), contact);
    }

    /**
     * 发送短信验证码实际逻辑
     */
    public boolean send(String smsCode, String contact) {
        try {
            // 从系统配置中获取短信平台配置
            String systemConfig = sdSysConfigService.queryConfigByNameValue("custom_sms", "sms");
            JSONObject config = new JSONObject();
            if (StringUtils.isNotBlank(systemConfig)) {
                config = JSONObject.parseObject(systemConfig);
            }
            // 截取 手机号前缀
            if (contact.startsWith("+86")) {
                contact = contact.substring(3);
            }
            // 获取 短信平台 请求地址
            String ipAddress = config.getString("ipAddress");
            if (StringUtils.isBlank(ipAddress)) {
                throw new SDExceptionEntity("CustomizeSmsService.sendSmsMsg ipAddress is null");
            }
            // 拼接 短信平台 请求接口
            String url = ipAddress.concat("/sms/submit");
            log.info("CustomizeSmsService.sendSmsMsg url: {}", url);
            // 获取 短信平台 用户名密码等必需参数
            String ecName = config.getString("ecName");
            if (StringUtils.isBlank(ecName)) {
                throw new SDExceptionEntity("CustomizeSmsService.sendSmsMsg ecName is null");
            }
            String apId = config.getString("apId");
            if (StringUtils.isBlank(apId)) {
                throw new SDExceptionEntity("CustomizeSmsService.sendSmsMsg apId is null");
            }
            String secretKey = config.getString("secretKey");
            if (StringUtils.isBlank(secretKey)) {
                throw new SDExceptionEntity("CustomizeSmsService.sendSmsMsg secretKey is null");
            }
            String sign = config.getString("sign");
            if (StringUtils.isBlank(sign)) {
                throw new SDExceptionEntity("CustomizeSmsService.sendSmsMsg sign is null");
            }
            // 获取 短信模板
            String content = config.getString("content");
            if (StringUtils.isBlank(content)) {
                throw new SDExceptionEntity("CustomizeSmsService.sendSmsMsg content is null");
            }
            // 组装请求参数
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("ecName", ecName);
            reqMap.put("apId", apId);
            reqMap.put("mobiles", contact);
            // 短信模板中替换验证码
            content = content.replace("${CODE}", smsCode);
            reqMap.put("content", content);
            reqMap.put("sign", sign);
            reqMap.put("addSerial", "");
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(ecName);
            stringBuffer.append(apId);
            stringBuffer.append(secretKey);
            stringBuffer.append(contact);
            stringBuffer.append(content);
            stringBuffer.append(sign);
            stringBuffer.append("");
            log.info("CustomizeSmsService.sendSmsMsg mac_stringBuffer:{}", stringBuffer.toString());
            // 计算mac
            String mac = DigestUtil.md5Hex(stringBuffer.toString());
            log.info("CustomizeSmsService.sendSmsMsg mac:{}", mac);
            reqMap.put("mac", mac);
            // 转换请求参数为json字符串
            String reqBody = JSON.toJSONString(reqMap);
            log.info("CustomizeSmsService.sendSmsMsg reqBody:{}", reqBody);
            // Base64编码
            String enReqBody = Base64.encodeBase64String(reqBody.getBytes());
            log.info("CustomizeSmsService.sendSmsMsg enReqBody:{}", enReqBody);
            // 发送请求
            String body = HttpUtil.post(url, enReqBody);
            log.info("CustomizeSmsService.sendSmsMsg send result: {}", body);
            if (StringUtils.isNotEmpty(body)) {
                // 解析返回结果
                JSONObject resultObj = JSON.parseObject(body);
                String rspcod = resultObj.getString("rspcod");
                boolean success = resultObj.getBoolean("success");
                log.info("CustomizeSmsService.sendSmsMsg send.rspcod: {}, success:{}", rspcod, success);
                if ("success".equals(rspcod) && success) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            log.error("send sms failed" + e.getMessage(), e);
            throw new SDExceptionEntity("send sms failed.");
        }
    }

    /**
     * 无需实现
     */
    @Override
    public boolean sendSmsMsgCustom(String title, List<String> user_id, Context context, List<UserItem> userItems, String contact) {
        return false;
    }
}
